<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-10-18
 * Time: 11:06
 */

namespace app\manage\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

// 引入ZBuilder
use app\common\model\DailyType as DailyTypeModel;
use think\Db;

class DailyType extends Admin
{
    //新闻分类列表
    public function lists( )
    {
        // 读取数据
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('qt_daily_type')
            ->where($map)
            ->where('pid','0')
            ->order('id desc')
            ->paginate();
        // 分页数据
        $page = $data_list->render();
        $btn_access1 = [
            'title' => '分类编辑',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-xs btn-default',
            'href' => url('edit', ['id' => '__id__']),
        ];
        $btn_access = [
            'title' => '新增日报分类',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-success',
            'href' => url('add'),
        ];
        $btn_access2 = [
            'title' => '删除分类',
            'icon' => 'fa fa-fw fa-trash-o',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href' => url('delete', ['id' => '__id__']),
        ];
        $btn_access3 = [
            'title' => '三级分类',
            'icon' => 'fa fa-fw fa-th-list',
            'class' => 'btn btn-xs btn-default',
            'href' => url('grandson_list',['id' => '__id__']),
        ];
        $btn_access4 = [
            'title' => '二级分类',
            'icon' => 'fa fa-fw fa-th-list',
            'class' => 'btn btn-xs btn-default',
            'href' => url('son_list', ['id' => '__id__']),
        ];
        $news_category = Db::name('qt_daily_type')->column('id,name');
        $post_category = Db::name('qt_post')->order('id asc')->column('id,title');
        $news_category['0'] = '顶级分类';
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', '编号', 'text')
            ->addColumn('name', '分类名称', 'text')
            ->addColumn('pid', '上级分类', 'status', '', $news_category)
            ->addColumn('sort', '排序', 'text')
            ->addColumn('type', '分类属性', 'status', '', ['1' => '固定分值', '2' => '手动输入'])
            ->addColumn('global', '类型', 'status', '', ['1' => '全局', '2' => '岗位'])
            ->addColumn('status', '状态', 'status', '', ['1' => '显示', '2' => '隐藏'])
            ->addColumn('right_button', '操作', 'btn')
            ->setSearchArea([
                ['text:2', 'name', '分类名称', 'like'],
            ])
            ->addTopButton('custom', $btn_access) // 添加顶部按钮
            ->addRightButton('edit', $btn_access1) // 添加右侧按钮
            ->addRightButton('delete', $btn_access2) // 添加右侧按钮
            ->addRightButton('list', $btn_access4) //
            ->addRightButton('single', $btn_access3) // 添加三级分类
            ->setPrimaryKey('id') // 设置主键名为username
            ->setPageTitle('分类列表')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }

    //添加日报审批分类
    public function add_single( )
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $result = $this->validate($data, 'DailyType.add');
            if (true !== $result) $this->error($result);
            $data['created_time'] = time();
            if($data['post_id'] == '0'){
                $data['global'] = '1';
            }
            $data['pid'] = '0';
            if (DailyTypeModel::create($data)) {
                $this->success('新增成功', url('lists'));
            } else {
                $this->error('新增失败');
            }
        } else {
            $groupRes = Db::name('qt_group')->whereIn('pid', ['0','1'])->column('id,name');
            $post_category = Db::name('qt_post')->order('id asc')->column('id,title');
            $post_category['0'] = '全局分类';
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['Linkage:7','team_id','所属团队','<code>请选择所属团队</code>',$groupRes,'',url('get_post'),'post_id'],
                        ['select:7','post_id','所属岗位'],
                        ['text:7', 'name', '分类名称'],
                        ['radio:', 'status', '状态', '', ['1' => '显示', '2' => '隐藏'], '1'],
                    ]
                )
                ->setPageTitle('新增一级分类')
                ->fetch();
        }
    }



    //添加日报审批分类
    public function add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $result = $this->validate($data, 'DailyType.add');
            if (true !== $result) $this->error($result);
            $data['created_time'] = time();
            $choiceData = explode("\n",$data['name']);
            foreach ($choiceData as $k=>$v){
                $dailyData[$k]['name'] = trim($v);
                $dailyData[$k]['pid'] = $data['pid'];
                $dailyData[$k]['num'] = $data['num'];
                $dailyData[$k]['status'] = $data['status'];
                $dailyData[$k]['sort'] = $data['sort'];
                $dailyData[$k]['type'] = $data['type'];
                $dailyData[$k]['global'] = $data['global'];
                $dailyData[$k]['created_time'] = time();
            }
            $insert = Db::name('qt_daily_type')->insertAll($dailyData);
            if ($insert) {
                $this->success('新增成功', 'lists');
            } else {
                $this->error('新增失败');
            }
        } else {

            $news_category = Db::name('qt_daily_type')->where('pid', '0')->column('id,name,global');
            $dailyData= [];
            foreach ($news_category as $key=>$value){
                if($value['global'] == '1'){
                    $type = '全局分类';
                }else{
                    $type = '岗位分类';
                }
                $dailyData[$value['id']] = $value['name'].'---'.$type;
            }
            $dailyData['0'] = '顶级分类';
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['select:7','pid','选择分类','<code>请选择所属分类</code>',$dailyData,'0'],
                        ['textarea:7', 'name', '分类选项', '<code>每一行为一个选项</code>'],
                        ['text:7', 'num', '分数值', '<code>如果为全局分类为最大值</code>','0'],
                        ['text:7', 'sort', '排序', '<code>0-100，默认50，越小越靠前</code>','50'],
                        ['radio:', 'global', '类型', '', ['2' => '岗位','1' => '全局'], '2'],
                        ['radio:','type','分类属性','',['1'=>'固定分值','2'=>'手动输入'],'1'],
                        ['radio:', 'status', '状态', '', ['1' => '显示', '2' => '隐藏'], '1'],

                    ]
                )
                ->setPageTitle('批量新增分类')
                ->fetch();
        }
    }


    /**
     * 获取当前团队下面的岗位
     * @param $team_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_post($team_id){
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $data= Db::name('qt_post')->where('team_id',$team_id)->field('id,title')->select(); //数据
        $result = [];
        foreach ($data as $key=>$value){
            $result[$key]['key'] = $value['id'];
            $result[$key]['value'] = $value['title'];
        }
        $arr['list'] = $result;
        return json($arr);
    }


    //编辑公告
    public function edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'DailyType.add');
            if (true !== $result) $this->error($result);

            if (DailyTypeModel::update($data)) {
                $this->success('编辑成功', 'lists');
            } else {
                $this->error('编辑失败');
            }
        } else {
            $info = DailyTypeModel::get($id);
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden', 'id', 'id'],
                        ['text:7', 'name', '标题'],
                        ['radio', 'type', '状态', '', [1 => '显示', 2 => '隐藏']]
                    ]
                )
                ->setFormData($info)
                ->setPageTitle('编辑分类')
                ->fetch();
        }
    }

    //删除新闻分类
    public function delete($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        $son = Db::name('qt_daily_type')->where('pid', $id)->count();
        if ($son > 0) {
            $this->error('请先删除下属分类', 'lists');
        }
        $re = DailyTypeModel::destroy($id);// 删除主键为1,2,3的数据
        if ($re) {
            $this->success('删除成功', 'lists');
        } else {
            $this->error('系统繁忙请稍后再试', 'lists');
        }

    }

    //新闻分类列表
    public function son_list($id = '' )
    {
        // 读取数据
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('qt_daily_type')
            ->where($map)
            ->where('pid',$id)
            ->order('id desc')
            ->paginate();
        // 分页数据
        $page = $data_list->render();
        $btn_access1 = [
            'title' => '分类编辑',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-xs btn-default',
            'href' => url('son_edit', ['id' => '__id__']),
        ];
        $btn_access = [
            'title' => '新增分类',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-success',
            'href' => url('son_add',['id'=>$id]),
        ];
        $btn_access2 = [
            'title' => '删除分类',
            'icon' => 'fa fa-fw fa-trash-o',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href' => url('son_delete', ['post_id'=>$id,'id' => '__id__']),
        ];
        $news_category = Db::name('qt_daily_type')->column('id,name');
        $post_category = Db::name('qt_post')->order('id asc')->column('id,title');
        $news_category['0'] = '顶级分类';
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', '编号', 'text')
            ->addColumn('name', '分类名称', 'text')
            ->addColumn('num', '分数值', 'text')
            ->addColumn('pid', '上级分类', 'status', '', $news_category)
            ->addColumn('type', '分类属性', 'status', '', ['1' => '固定分值', '2' => '手动输入'])
            ->addColumn('status', '状态', 'status', '', ['1' => '显示', '2' => '隐藏'])
            ->addColumn('right_button', '操作', 'btn')
            ->setSearchArea([
                ['select:2', 'da.post_id', '所属岗位', 'eq', '', $post_category],
                ['text:2', 'da.name', '分类名称', 'like'],
            ])
            ->addTopButton('custom', $btn_access) // 添加顶部按钮
            ->addRightButton('edit', $btn_access1) // 添加右侧按钮
            ->addRightButton('delete', $btn_access2) // 添加右侧按钮
            ->setPrimaryKey('id') // 设置主键名为username
            ->setPageTitle('分类列表')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }


    //添加日报审批分类
    public function son_add($id = '')
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $result = $this->validate($data, 'DailyType.add');
            if (true !== $result) $this->error($result);
            $data['created_time'] = time();
            if (DailyTypeModel::create($data)) {
                $this->success('新增成功', url('son_list',['id'=>$id]));
            } else {
                $this->error('新增失败');
            }
        } else {
            $dailyRes = Db::name('qt_daily_type')->where('id',$id)->find();
            if(empty($dailyRes)){
                $dailyRes['post_id'] = '0';
            }
            $news_category = Db::name('qt_daily_type')->where('post_id', $dailyRes['post_id'])->where('pid','o')->column('id,name,global');
            $dailyData= [];
            foreach ($news_category as $key=>$value){
                if($value['global'] == '1'){
                    $type = '全局分类';
                }else{
                    $type = '岗位分类';
                }
                $dailyData[$value['id']] = $value['name'].'---'.$type;
            }
            $dailyData['0'] = '顶级分类';
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['text:7', 'name', '分类名称'],
                        ['text:7', 'num', '分数值', '','0'],
                        ['text:7', 'min', '最小值', '<code>手动输入分值时，请填写分数范围</code>','0'],
                        ['text:7', 'max', '最大值', '<code>手动输入分值时，请填写分数范围</code>','20'],
                        ['textarea:7', 'explain', '说明', '<code>当前分类的说明</code>'],
                        ['select:7','pid','选择分类','<code>请选择所属分类</code>',$dailyData,$id],
                        ['radio:','type','分类属性','',['1'=>'固定分值','2'=>'手动输入'],'1'],
                        ['radio:', 'status', '状态', '', ['1' => '显示', '2' => '隐藏'], '1'],
                    ]
                )
                ->setPageTitle('新增分类')
                ->fetch();
        }
    }

    //三级分类列表
    public function grandson_list($id = '' )
    {
        // 读取数据
        $map = $this->getMap();
        // 数据列表
        $pids = Db::name('qt_daily_type')
            ->where($map)
            ->where('pid',$id)
            ->column('id');

        if(!empty($pids)){
            $data_list = Db::name('qt_daily_type')->whereIn('pid',$pids)->order('id desc')->paginate();
            $page = $data_list->render();
        }else{
            $page = '';
            $data_list = [];
        }
        // 分页数据
        $btn_access1 = [
            'title' => '分类编辑',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-xs btn-default',
            'href' => url('grandson_edit', ['id' => '__id__']),
        ];
        $btn_access = [
            'title' => '新增分类',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-success',
            'href' => url('grandson_add',['id'=>$id]),
        ];
        $btn_access2 = [
            'title' => '删除分类',
            'icon' => 'fa fa-fw fa-trash-o',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href' => url('grandson_delete', ['post_id'=>$id,'id' => '__id__']),
        ];
        $news_category = Db::name('qt_daily_type')->column('id,name');
        $post_category = Db::name('qt_post')->order('id asc')->column('id,title');
        $news_category['0'] = '顶级分类';
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', '编号', 'text')
            ->addColumn('name', '分类名称', 'text')
            ->addColumn('num', '分数值', 'text')
            ->addColumn('pid', '上级分类', 'status', '', $news_category)
            ->addColumn('type', '分类属性', 'status', '', ['1' => '固定分值', '2' => '手动输入'])
            ->addColumn('status', '状态', 'status', '', ['1' => '显示', '2' => '隐藏'])
            ->addColumn('right_button', '操作', 'btn')
            ->setSearchArea([
                ['select:2', 'da.post_id', '所属岗位', 'eq', '', $post_category],
                ['text:2', 'da.name', '分类名称', 'like'],
            ])
            ->addTopButton('custom', $btn_access) // 添加顶部按钮
            ->addRightButton('edit', $btn_access1) // 添加右侧按钮
            ->addRightButton('delete', $btn_access2) // 添加右侧按钮
            ->setPrimaryKey('id') // 设置主键名为username
            ->setPageTitle('分类列表')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }


    //修改日报二级分类
    public function grandson_edit($id = '')
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            $info = DailyTypeModel::get($id);
            // 表单数据
            $data = $this->request->post();
            if (DailyTypeModel::where('id',$data['id'])->update($data) !== false) {
                $topId = Db::name('qt_daily_type')->where('id',$info['pid'])->value('pid');
                $this->success('修改成功', url('grandson_list',['id'=>$topId]));
            } else {
                $this->error('修改失败');
            }
        } else {
            $info = DailyTypeModel::get($id);
            $topId = Db::name('qt_daily_type')->where('id',$info['pid'])->value('pid');
            $dailyData = Db::name('qt_daily_type')->where('pid',$topId)->column('name','id');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden','id',$id],
                        ['select:7','pid','选择分类','<code>请选择所属分类</code>',$dailyData],
                        ['text:7', 'name', '分类名称'],
                        ['radio:', 'status', '状态', '', ['1' => '显示', '2' => '隐藏']],
                    ]
                )
                ->setPageTitle('修改分类')
                ->setFormData($info)
                ->fetch();
        }
    }














    /**
     * 添加福利分三级分类
     * @param string $id [顶级分类ID]
     */
    public function grandson_add($id = '')
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            if(empty($data['name'])){
                $this->error('请填写选项');
            }
            if(!empty($data['name'])){
                //删除投票选项并创建新的投票选项
                $choiceData = explode("\n",$data['name']);
                $inserData = [];
                foreach ($choiceData as $key=>$value){
                    $inserData[$key]['pid'] = $data['pid'];
                    $inserData[$key]['name'] = $value;
                    $inserData[$key]['created_time'] = time();
                }
                try{
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_daily_type')->insertAll($inserData);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->error('编辑失败');
                }
            }
            $this->success('新增成功', url('grandson_list',['id'=>$id]));
        } else {
            $dailyData = Db::name('qt_daily_type')->where('pid',$id)->column('name','id');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['select:7','pid','选择分类','<code>请选择所属分类</code>',$dailyData],
                        ['textarea:7', 'name', '三级分类名称', '<code>当前分类的说明，每一行为一个分类</code>'],
                        ['radio:', 'status', '状态', '', ['1' => '显示', '2' => '隐藏'], '1'],
                    ]
                )
                ->setPageTitle('新增三级分类')
                ->fetch();
        }
    }


    //修改日报二级分类
    public function son_edit($id = '')
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            $info = DailyTypeModel::get($id);
            // 表单数据
            $data = $this->request->post();
            $result = $this->validate($data, 'DailyType.add');
            if (true !== $result) $this->error($result);
            if (DailyTypeModel::where('id',$data['id'])->update($data)) {
                $this->success('修改成功', url('son_list',['id'=>$info['pid']]));
            } else {
                $this->error('修改失败');
            }
        } else {
            $info = DailyTypeModel::get($id);
            $news_category = Db::name('qt_daily_type')->where('post_id', $info['post_id'])->where('pid','o')->column('id,name,global');
            $dailyData= [];
            foreach ($news_category as $key=>$value){
                if($value['global'] == '1'){
                    $type = '全局分类';
                }else{
                    $type = '岗位分类';
                }
                $dailyData[$value['id']] = $value['name'].'---'.$type;
            }
            $dailyData['0'] = '顶级分类';
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden','id',$id],
                        ['select:7','pid','选择分类','<code>请选择所属分类</code>',$dailyData],
                        ['text:7', 'name', '分类名称'],
                        ['text:7', 'num', '分数值', ''],
                        ['text:7', 'min', '最小值', '<code>手动输入分值时，请填写分数范围</code>'],
                        ['text:7', 'max', '最大值', '<code>手动输入分值时，请填写分数范围</code>'],
                        ['textarea:7', 'explain', '说明', '<code>当前分类的说明</code>'],
                        ['radio:','type','分类属性','',['1'=>'固定分值','2'=>'手动输入']],
                        ['radio:', 'status', '状态', '', ['1' => '显示', '2' => '隐藏']],
                    ]
                )
                ->setPageTitle('修改分类')
                ->setFormData($info)
                ->fetch();
        }
    }


    //删除三级分类
    public function grandson_delete($id = null,$post_id  = '')
    {
        if ($id === null) $this->error('缺少参数');
        $re = DailyTypeModel::destroy($id);// 删除主键为1,2,3的数据
        if ($re) {
            $this->success('删除成功', url('grandson_list',['id'=>$post_id]));
        } else {
            $this->error('系统繁忙请稍后再试', url('grandson_list',['id'=>$post_id]));
        }

    }

    //删除二级分类
    public function son_delete($id = null,$post_id  = '')
    {
        if ($id === null) $this->error('缺少参数');
        $re = DailyTypeModel::destroy($id);// 删除主键为1,2,3的数据
        if ($re) {
            $this->success('删除成功', url('son_list',['id'=>$post_id]));
        } else {
            $this->error('系统繁忙请稍后再试', url('son_list',['id'=>$post_id]));
        }

    }


}